package com.cs.pk.codestriker;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import org.eclipse.swt.widgets.Combo;

import com.cs.pk.utils.ClearCaseException;
import com.cs.pk.utils.StreamReader;
import com.cs.pk.utils.UtilRepository;

public class Views extends AbstractPopulateList{

	private Combo views = null;
	public Views(Object component) {
		super(component);
		views = (Combo)component;
	}

//	public static void main(String args[]) throws IOException,
//			InterruptedException {
//         // new Views().getViews();
//          
//         
//		
////		ProcessBuilder builder = new ProcessBuilder(new String[] { "cmd.exe", "/E:1900", "/C", "MyBat.bat"},
////                new String[] { "flavour=strawberry", "font=Stone"},
////                "C:\\SomeDirectory" );
//		//builder.directory(new File("M:\\Prabhatk_GET_VOD_Proj_2"));
//		//builder.command(new String[] {"cleartool lsview -cview -s"});
//		//System.out.println("prabhatk: starting "+builder.directory());
//		//Process cleartool = Runtime.getRuntime().exec("D:/workspace/codestriker/clearcase/view.bat M: M:/Prabhatk_GET_VOD_Proj_2");
//		//System.out.println("prabhatk: starting "+builder.directory());
//		//InputStream er = cleartool.getInputStream();
//		//OutputStream os = cleartool.getOutputStream();
//		//InputStream er = cleartool.getErrorStream();
//		//System.out.println("prabhatk: writing to the shell ");
////		os.write(new String("M:").getBytes());
////		os.flush();
////		os.write(new String("M:\\Prabhatk_GET_VOD_Proj_2").getBytes());
////		os.flush();
//		//os.close();
//		//System.out.println("prabhatk: started reading ");
//	//	InputStream in = is.getInputStream();
//       // int c;
//        //System.out.println("prabhatk: error");
//      //  while ((c = er.read()) != -1) {
//      //      System.out.print((char)c);
//      //  }
//        //is.close();
//       // System.out.println("prabhatk: end ");
//        //os.write(new String("M:").getBytes());
//		//os.flush();
//		//os.write(new String("M:\\Prabhatk_GET_VOD_Proj_2").getBytes());
//		//os.flush();
//       // System.out.println();
//      //  int c;
////        System.out.println("prabhatk: output ");
////        while ((c = is.read()) != -1) {
////            System.out.print(c);
////        }
////        is.close();
//		//StreamReader reader = new StreamReader(is);
//
//		//reader.start();
//		//cleartool.waitFor();
//		//reader.join();
//        
//		//String result = reader.getResult();
//		
//		//System.out.println("result "+result);
////		StringBuffer sb = new StringBuffer();
////		try {
////			byte b[] = new byte[128];
////			int n = 0;
////			while ((n = is.read(b)) != -1) {
////				sb.append(new String(b, 0, n));
////				b = new byte[128];
////			}
////		} catch (IOException e) {
////			e.printStackTrace();
////		}
////		
////		System.out.println("prabhatk: started reading error ");
////		
////		StreamReader errorReader = new StreamReader(er);
////
////		errorReader.start();
////		//cleartool.waitFor();
////		//errorReader.join();
////
////		String error = errorReader.getResult();
////		
////		System.out.println("error "+error);
//		
//	}

	private final String QUERY_CMD = "REG QUERY ";

	private final String DRIVE_PARAM = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Mvfs\\Parameters /v drive";

	private final String PARSE_TOKEN = "REG_SZ";
	
	//private final String CONF_BAT_FILE = "/clearcase/view.bat";
	
	//private final String VIEW_CMD ="lsview -cview -s";

	private String getDrive() throws IOException, InterruptedException {
		Process process = Runtime.getRuntime().exec(QUERY_CMD + DRIVE_PARAM);
		StreamReader reader = new StreamReader(process.getInputStream(),"INPUT");

		reader.start();
		process.waitFor();
		reader.join();

		String result = reader.getResult();
		int p = result.indexOf(PARSE_TOKEN);
		if (p == -1) {
			 throw new IOException("Clearcase drive is not register with windows.");
		}
		return result.substring(p + PARSE_TOKEN.length()).trim();
	}
	
//	public List getViews() {
//		ArrayList vList = new ArrayList();
//		try {
//			String drive = getDrive();
//			if(drive!= null) {
//				File drive_ = new File(drive+":\\");
//				File childs[] = drive_.listFiles(new FileFilter() {
//					public boolean accept(File arg0) {
//						return arg0.isDirectory();
//					}					
//				});
//				String view = null;
//				for(int i=0;i<childs.length;i++) {
//					view = runBatFile(drive+":", childs[i].getAbsolutePath());
//					if(view!=null) {
//						vList.add(view);
//					}
////					rough();
////					break;
//				}
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		//return vList.toArray(new String[vList.size()]);
//		return vList;
//	}
	
	
//	private void rough() {
//	   //ProcessBuilder builder = new ProcessBuilder(new String[] { "cmd.exe"});
//		 //Process p = Runtime.getRuntime().exec("D:/Eclipse3.4/plugins/codestriker_1.0.0.jar/clearcase/view.bat");
//		//builder.directory(new File("./"));
//		//builder.command(new String[] {"cleartool lsview -cview -s"});
//		Map map = System.getenv();
//		Set kset = map.keySet();
//		for (Iterator iterator = kset.iterator(); iterator.hasNext();) {
//			String key = (String) iterator.next();
//			System.out.println(key +" = "+System.getProperty(key));
//			
//		}
//		
//		try {
//		  System.out.println("prabhatk: url "+Views.class.getResource("Views.class"));
//		  //System.out.println("prabhatk: url "+Views.class.getResource("Views.class"));
//		}catch(Exception e) {
//			e.printStackTrace();
//		}
//		//System.out.println("prabhatk: starting "+builder.directory());
//		System.out.println("prabhatk: user.dir "+System.getProperty("user.dir"));
//		System.setProperty("java.class.path", System.getProperty("java.class.path")+";D:/Eclipse3.4/plugins/codestriker_1.0.0.jar");
//		System.out.println("prabhatk: java.class.path "+System.getProperty("java.class.path"));
//		
//		try {
//			//System.
//		    Process cleartool = Runtime.getRuntime().exec("view.bat");//builder.start();//Runtime.getRuntime().exec("D:/workspace/codestriker/clearcase/view.bat M: M:/Prabhatk_GET_VOD_Proj_2");
//			InputStream is = cleartool.getInputStream();
//			//OutputStream os = cleartool.getOutputStream();
//			InputStream er = cleartool.getErrorStream();
//			
//			//	InputStream in = is.getInputStream();
//			 int c;
//			System.out.println("prabhatk: info");
//			  while ((c = is.read()) != -1) {
//			      System.out.print((char)c);
//			  }
//			is.close();
//			System.out.println();
//			System.out.println("prabhatk: error");
//			  while ((c = er.read()) != -1) {
//			      System.out.print((char)c);
//			  }
//			  er.close();
//		}catch(Exception e) {
//			e.printStackTrace();
//		}
//	}

	
	protected void populate(Object payload) throws ClearCaseException, IOException, InterruptedException {
			String drive = getDrive();
			UtilRepository.DRIVE = drive;
			if(drive!= null) {
				File drive_ = new File(drive+":\\");
				File childs[] = drive_.listFiles(new FileFilter() {
					public boolean accept(File arg0) {
						return arg0.isDirectory();
					}					
				});
				String view = null;
				for(int i=0;i<childs.length;i++) {
					view = runBatFile(new String[] {/*Activator.getDefault().clearcase_file_path, "view",*/drive+":","cd "+ childs[i].getAbsolutePath(),"cleartool lsview -cview -s"});
					if(view!=null) {
						UtilRepository.updateViewDirectoryRepository(view, childs[i].getAbsolutePath());
                        views.add(view);
					}
				}
			}
	}

	public String filterOutput() {
		if(result!=null) {
			String tokens[] = result.trim().split("\n");
				return tokens[tokens.length-1];
		}
		return null;
	}

	protected int getRepositoryType() {
		return UtilRepository.VIEW_REPOSITORY;
	}

	public void clear() {
         views.removeAll();		
	}
}
